<template>
  <div class="applications">
    <a-tabs
        v-model:activeKey="activeKey"
        type="editable-card"
        hide-add
        size="small"
        :tabBarGutter="0"
        @edit="onEdit"
        v-if="menuType == 1"
    >
      <a-tab-pane
          v-for="(pane, index) of panes"
          :key="pane.id"
          :closable="index > 0"
      >
        <!-- 自定义标题 -->
        <template #tab>
          <span class="pane-title">
            <div class="pane-icon">
              <img class="image" v-if="pane.app_logo" :src="pane.app_logo"/>
              <cu-icon v-else class="icon" type="org-menu-yingyong"></cu-icon>
            </div>
            <span class="title">{{ pane.app_name }}</span>
          </span>
        </template>
        <!-- 内容 -->
        <section class="content">
          <all-apps
              v-if="pane.id === 0"
              :refresh="refreshTrigger"
              @appClick="handleAppClick"
              @getAllApp="getAllApp"
          />
          <iframe-page
              v-else
              :content="pane"
              :current="activeKey"
              :refresh="refreshTrigger"
              @open="handleOtherAppOpen"
          />
        </section>
      </a-tab-pane>

      <!-- 自定义操作栏 -->
      <!-- <template #rightExtra>
        <a-dropdown>
          <a-button @click.prevent type="text">
            <template #icon>
              <MoreOutlined />
            </template>
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item @click="refreshPane" v-if="activeKey != 0">
                刷新当前应用标签
              </a-menu-item>
              <a-menu-item @click="closeOtherPane('both')">
                关闭其他应用标签
              </a-menu-item>
              <a-menu-item @click="closeOtherPane('left')">
                关闭左侧应用标签
              </a-menu-item>
              <a-menu-item @click="closeOtherPane('right')">
                关闭右侧应用标签
              </a-menu-item>
              <a-menu-item @click="closeAllPane">
                关闭所有应用标签
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template> -->
    </a-tabs>
    <div style="height: 100%" v-else>
      <all-apps
          :refresh="refreshTrigger"
          :pcMenuType="menuType"
          @appClick="handleAppClick"
          @getAllApp="getAllApp"
      />
    </div>
    <check-building
        :visible="checkBuildingVisible"
        @fail="checkBuildingVisible = false"
        @success="handleBuildingChecked"
    />
  </div>
</template>

<script>
import {defineComponent, reactive, computed, ref, toRaw, watch} from "vue";
import AllApps from "./modules/AllApps.vue";
import IframePage from "./modules/IframePage.vue";
import {MoreOutlined, CloseOutlined} from "@ant-design/icons-vue";
import CheckBuilding from "./modules/CheckBuilding.vue";
import store from "../../../store";
import {message} from "ant-design-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
// import {MICRO_APPS} from "../../../micro_apps/index.js";
import defaultSetting from "../../../common/utils/defaultSetting";
import {useRoute} from "vue-router";
import RouteUtils from "../../../router/router.utils";

const defaultPane = {id: 0, app_name: "应用中心"};

export default defineComponent({
  name: "applications",
  components: {
    AllApps,
    IframePage,
    CheckBuilding,
    MoreOutlined,
    CloseOutlined,
  },
  setup() {
    const activeKey = ref(0);
    const panes = reactive([defaultPane]);
    const route = useRoute();
    const showType = ref(route.query.show);

    const menuType = computed(() => store.getters.userInfo.pc_menu_type);

    // 点击并打开应用
    let params = {};
    const handleAppClick = (app) => {
      if (app.app_type == 0) {
        params = {appId: app.id, appUrl: app.app_url};
        // 新窗口打开
        if (app.app_label == "property") {
          // 跳转物业,弹框选择楼宇再获取链接跳转
          const {
            checkedBuildingCount,
            checkedBuildings,
            permissionBuildings,
          } = store.getters.buildingInfo;
          if (!checkedBuildingCount) {
            message.error("您还未添加楼宇！");
          } else {
            if (checkedBuildingCount > 1) {
              checkBuildingVisible.value = true;
            } else {
              params.buildId = checkedBuildings[0];
              permissionBuildings.forEach((item) => {
                if (item.build.includes(params.buildId)) {
                  params.villageId = item.id;
                }
              });
              handleBuildingChecked();
            }
          }
          return;
        }
        window.open(app.app_url);
      } else {
        if (menuType.value == 2) {
          console.log("app", app);
          RouteUtils.onMenuChange({menu: app});
          return;
        }

        if (app.app_micro) {
          app.app_url = getInnerLink(app);
        }
        // tab页
        const index = panes.findIndex((item) => item.id == app.id);
        if (index === -1) {
          panes.push(app);
        }
        activeKey.value = app.id;
      }
    };

    // 组装内链链接
    const getInnerLink = (app) => {
      // console.log("MICRO_APPS", MICRO_APPS);
      let url = app.app_url;
      if (url.indexOf("http") > -1) {
        return url;
      }
      // todo...
      // const belongApp = MICRO_APPS.find((item) => item.name === app.app_micro);
      // if (belongApp) {
      //   // if (["workProperty"].includes(belongApp.name)) {
      //   //   //某些应用打开时需要收起菜单
      //   //   store.dispatch("SetCollapsed", true);
      //   // }
      //   if (utils.isEnv()) {
      //     url = `http:${belongApp.entry}/#/${app.app_url}`;
      //   } else {
      //     url = `${defaultSetting.requestDomain + belongApp.entry}/#/${
      //         app.app_url
      //     }`;
      //   }
      // }
      return url;
    };

    const allApps = ref([]);
    const getAllApp = (detail) => {
      allApps.value = detail.appList;
    };

    // 在应用内打开其他iframe应用
    const handleOtherAppOpen = (detail) => {
      let {app} = detail;
      let url = app.app_url;
      const appItem = allApps.value.find(
          (item) => item.app_micro == app.app_micro
      );
      if (appItem) {
        app = {...appItem};
        app.app_url = url;
        app.app_url = getInnerLink(app);
        const index = panes.findIndex((item) => item.id == app.id);
        if (index === -1) {
          panes.push(app);
        }
        activeKey.value = app.id;
      } else {
        message.warning("您没有权限访问~");
      }
    };

    // 选择应用弹窗
    const checkBuildingVisible = ref(false);

    const handleBuildingChecked = (info) => {
      if (info) {
        params = {
          ...params,
          ...info,
        };
      }
      request.post("/village", "/app/getPropertyUrl", params).then((res) => {
        checkBuildingVisible.value = false;
        window.open(res.url);
      });
    };

    // 删除标签
    const onEdit = (targetKey, action) => {
      if (action == "remove") {
        const index = panes.findIndex((item) => item.id == targetKey);
        panes.splice(index, 1);
        activeKey.value = panes[index - 1].id;
      }
    };

    // 刷新当前应用
    const refreshTrigger = ref(0);
    const refreshPane = () => {
      refreshTrigger.value++;
    };

    // 关闭其他标签页
    const closeOtherPane = (type) => {
      const index = panes.findIndex((item) => item.id == activeKey.value);
      if (panes.length > 1) {
        // 关闭左侧
        if (type == "left") {
          closeLeft(index);
          return;
        }
        // 关闭右侧
        if (type == "right") {
          closeRight(index);
          return;
        }
        // 关闭其他
        if (type == "both") {
          closeRight(index);
          closeLeft(index);
          return;
        }
      }
    };
    const closeLeft = (index) => {
      if (index > 1) {
        panes.splice(1, index - 1);
      }
    };
    const closeRight = (index) => {
      if (index < panes.length - 1) {
        panes.splice(index + 1, panes.length - index - 1);
      }
    };

    // 关闭所有应用页
    const closeAllPane = () => {
      if (panes.length > 1) {
        panes.splice(1, panes.length - 1);
        activeKey.value = 0;
      }
    };

    watch(
        [() => route.name, () => route.query],
        ([name, query], [preName, preQuery]) => {
          if (name == "applications") {
            showType.value = query.show || "";
            if (name == preName) {
              // 路由参数变化
              closeAllPane();
            }
          }
        }
    );

    return {
      activeKey,
      panes,
      refreshTrigger,
      checkBuildingVisible,
      menuType,
      handleAppClick,
      onEdit,
      refreshPane,
      closeAllPane,
      closeOtherPane,
      handleBuildingChecked,
      handleOtherAppOpen,
      getAllApp,
    };
  },
});
</script>

<style lang="less" scoped>
@iconSize: 14px;
.applications {
  width: 100%;
  height: 100%;
  background: #e6e7e8;

  &:deep(.ant-tabs-bar) {
    margin: 0px;
    position: relative;
    width: 100%;
  }

  :deep(.ant-tabs-tab) {
    background: transparent !important;
    border: none !important;
    position: relative;
    height: 40px;

    &:not(:last-child) {
      border-right: 1px solid #f5f6f7 !important;
      // &::after {
      //   content: "";
      //   position: absolute;
      //   right: 0;
      //   top: 5px;
      //   bottom: 5px;
      //   width: 1px;
      //   background: #ccc;
      // }
    }
  }

  :deep(.ant-tabs-tab-active) {
    background: #f5f6f7 !important;
    border-bottom: 1px solid #f5f6f7 !important;
  }

  .pane-title {
    position: relative;

    .pane-icon {
      width: @iconSize;
      height: @iconSize;
      border-radius: 4px;
      background: @primary-color;
      display: inline-block;
      overflow: hidden;
      margin-right: 6px;
      position: relative;
      top: 50%;
      transform: translateY(20%);
      overflow: hidden;

      .image {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
      }

      .icon {
        position: absolute;
        font-size: 10px;
        color: #fff;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        line-height: @iconSize;
        vertical-align: middle;
        text-align: center;
      }
    }

    .title {
      min-width: 120px;
      display: inline-block;
      // overflow: hidden;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      // word-break: break-all;
    }

    // display: flex;
  }

  .content {
    // padding: 10px;
    height: calc(~"100vh - 40px");
    overflow: auto;
  }
}
</style>
